<script lang="ts" setup>
import { ref } from 'vue'
import type { Ref } from 'vue'
import { loginFn } from '@/api/user'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
// 导入全局状态
import { useUserStore } from '@/stores/user'

// 创建全局状态的接收
const user = useUserStore()

const router = useRouter()

// 用来提交表单登录的方法
function onSubmit() {
  loginFn({
    loginname: loginname.value,
    password: password.value
  }).then(res => {
    console.log(res);
    showToast(res.data.message)
    if (res.data.code == '200') {

      // 登录成功
      // 1. 保存 token
      localStorage.setItem('token', res.data.data.token)
      // 2. 保存用户 id
      localStorage.setItem('userid', res.data.data.userid)
      // 3. 保存用户登录状态
      localStorage.setItem('loginState', 'true')

      // 在全局状态中保存用户数据
      user.changeLoginState(true)
      user.changeUserId(res.data.data.userid)

      router.back()
    }
  })
}
// 定义用户名和密码
const loginname: Ref<string> = ref('')
const password: Ref<string> = ref('')

</script>
<template>
  <div class="box">
    <header class="header">登录</header>

    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model="loginname" name="用户名" label="用户名" placeholder="请输入用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" />

        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="请输入密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="danger" native-type="submit">
          登录
        </van-button>
      </div>
      <div style="margin: 16px;">
        <van-button @click="$router.push('/register')" round block type="success">
          去注册
        </van-button>
      </div>
    </van-form>

  </div>
</template>
